<?php
/**
 * | 节程 [ 节程赋能开发者，助力企业发展 ]
 * +----------------------------------------------------------------------
 *  | Copyright (c) 2020~2029 温州惊蛰网络科技有限公司 All rights reserved.
 * +----------------------------------------------------------------------
 *  | Licensed 节程并不是自由软件，未经许可不能去掉节程相关版权
 * +----------------------------------------------------------------------
 */

namespace app\shop_admin\service;

use app\shop_admin\model\Express;
use app\shop_admin\model\Order;
use app\shop_admin\model\OrderCommodity;
use app\shop_admin\model\ReceiptsTemplate;
use app\shop_admin\model\ReceiptsPrinter;
use Exception;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;

class Import
{
    /**
     * 使用PHPEXECL导入
     * @param string $filePath 文件路径地址
     * @param int $sheet 文件的sheet序号，从0开始
     * @param int $columnCnt 每个sheet读多少个字段
     * @param array $options
     * @return array 二维数组，每一个元素为一个数组，表示一列的数据。
     *               键为A,B,C的列号，值为该行所对应列的单元格内的值，第一个元素为表头
     * @throws Exception
     */
    public function importExecl(string $filePath = '', int $sheet = 0, int $columnCnt = 0, &$options = [])
    {
        try {
            /* 转码 */
            $filePath = iconv("utf-8", "gb2312", $filePath);
            if (!file_exists($filePath)) {
                throw new \Exception('文件不存在!');
            }
            /** @var Xlsx $objRead */
            $objRead = IOFactory::createReader('Xlsx');

            if (!$objRead->canRead($filePath)) {
                /** @var Xls $objRead */
                $objRead = IOFactory::createReader('Xls');

                if (!$objRead->canRead($filePath)) {
                    throw new \Exception('只支持导入Excel文件！');
                }
            }

            /* 如果不需要获取特殊操作，则只读内容，可以大幅度提升读取Excel效率 */
            empty($options) && $objRead->setReadDataOnly(true);
            /* 建立excel对象 */
            $obj = $objRead->load($filePath);
            /* 获取指定的sheet表 */
            $currSheet = $obj->getSheet($sheet);

            if (isset($options['mergeCells'])) {
                /* 读取合并行列 */
                $options['mergeCells'] = $currSheet->getMergeCells();
            }

            if (0 == $columnCnt) {
                /* 取得最大的列号 */
                $columnH = $currSheet->getHighestColumn();
                /* 兼容原逻辑，循环时使用的是小于等于 */
                $columnCnt = Coordinate::columnIndexFromString($columnH);
            }

            /* 获取总行数 */
            $rowCnt = $currSheet->getHighestRow();
            $data = [];

            /* 读取内容 */
            for ($_row = 2; $_row <= $rowCnt; $_row++) {
                $isNull = true;

                for ($_column = 1; $_column <= $columnCnt; $_column++) {
                    $cellName = Coordinate::stringFromColumnIndex($_column);
                    $cellId = $cellName . $_row;
                    $data[$_row][$cellName] = trim($currSheet->getCell($cellId)->getFormattedValue());
                    if (!empty($data[$_row][$cellName])) {
                        $isNull = false;
                    }
                }
                if ($isNull) {
                    unset($data[$_row]);
                }
            }
            $data = $this->array_unique_fb($data);
            foreach ($data as $v) {
                $find = Order::where('order_no', $v['0'])->find();
                if (empty($find) || !in_array($find->getData('status'),[2])) continue;
                $id = $find['id'];
                $name = Express::where('code', $v['1'])->value('name');
                OrderCommodity::where('order_id', $id)->update(['express_company' => $name, 'logistics_no' => $v['2'], "status" => 3]);
                Order::update(['status' => 3], ['id' => $id]);
                //(new ReceiptsService())->implementation_plan([$id]);
            }
            return [HTTP_SUCCESS, "成功"];
        } catch (\Exception $e) {
            return [HTTP_INVALID, $e->getMessage()];
        }
    }

    private function array_unique_fb($array)
    {
        foreach ($array as $v) {
            $v = join(", ", $v);
            $temp[] = $v;
        }
        $temp = array_unique($temp);
        foreach ($temp as $k => $v) {
            $temp[$k] = explode(", ", $v);
        }
        return $temp;
    }
}